/*
 * Copyright (C) 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.xbaistack.common;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.convert.ConversionService;
import top.xbaistack.config.SpringContextHolder;

/**
 * WebSocket 统一请求消息，前端在 WebSocket 通讯中统一传递固定的 JSON 格式，然后统一转换成此对象。
 *
 * <pre>
 *   {"type": "xxx", "payload": <Object>}
 * </pre>
 *
 * 其中的 <code>roomId</code> 和 <code>playerId</code> 由后端获取后设置进来，非前端传递。
 *
 * @author xbaistack
 * @since 2025/03/25
 */
@Getter
@Setter
public class WebSocketRequest {
    private String type;
    private String roomId;
    private String playerId;
    private Object payload;

    public <T> T dataOf(Class<T> type) {
        // 避免数据为空的情况
        if (ObjectUtils.isEmpty(payload)) {
            return null;
        }

        // 尝试通过 Spring 内部转换器进行数据转换
        final ConversionService conversion = SpringContextHolder.getBean(ConversionService.class);
        if (conversion != null && conversion.canConvert(payload.getClass(), type)) {
            return conversion.convert(payload, type);
        }

        // 否则使用 ApacheBeanUtils 中的工具类进行数据转换
        return (T) ConvertUtils.convert(payload, type);
    }
}
